
#include <string.h>
#include <stdlib.h>
#include "debug.h"
#include "SQLiteInterface.h"

SQLiteInterface *SQLiteInterface::sqlite_iface_singleton = NULL;

/** Get singleton instance (prevents double initialisation) */
SQLiteInterface &SQLiteInterface::getInstance()
{
   if (sqlite_iface_singleton == NULL)
      sqlite_iface_singleton = new SQLiteInterface();
   return *sqlite_iface_singleton;
}

/** Initialises the SQLite library, checking for the 'compiled with
 * thread-safety' option. */
SQLiteInterface::SQLiteInterface()
{
   sqlite3_initialize();
   if (!(sqlite3_threadsafe()))
      errprint("Thread safety off?!?! Please recompile SQLite with thread safety on.");
}

/** Finalises the SQLite library. */
SQLiteInterface::~SQLiteInterface()
{
   sqlite3_shutdown();
}

/** Generates an appropriately printed SQLite error message (the macro
 * should be used to call this). */
void SQLiteInterface::func_CheckSQLiteError(sqlite3 *sdb, const char *message, const char *fpretty, int line)
{
   const char *errmsg = sqlite3_errmsg(sdb);
   char *errbuf = (char *)malloc(sizeof(char)*(strlen(errmsg)+strlen(message)+1));
   if (errbuf)
   {
      strcpy(errbuf, message);
      strcat(errbuf, errmsg);
      errprintpd("%s", fpretty, line, errbuf);
      free(errbuf);
   } else
   {
      errprintpd("%s", fpretty, line, errmsg);
   }
}

/** Destroy the singleton. */
void SQLiteInterface::destroyInstance()
{
   delete sqlite_iface_singleton;
   sqlite_iface_singleton = NULL;
}
